layui.config({
	base: "static/layui/module/"
}).extend({
	dynamicCondition: 'dynamicCondition/dynamicCondition',
	excel: 'excel/excel'
}).use(['form','layer','jquery','table','laydate','upload','element','laytpl','excel','dynamicCondition'],function() {
	var form = layui.form,
		layer = layui.layer,
		$ = layui.jquery,
		table = layui.table,
		laydate = layui.laydate,
		upload = layui.upload,
		element = layui.element,
		laytpl = layui.laytpl,
		dynamicCondition = layui.dynamicCondition,
		excel = layui.excel;

	var tableSelect = undefined;

	table.render({
        elem:'#table'
    	,height: 'full-120'
    	,url:'/manage/process_price_order/list_order'
	    ,method:'post'
        ,page: true //开启分页
	    ,limit: 10
	    ,limits: [10,15,20,30,40,50,100]
	    ,loading: true
        ,cols: [[ //表头
        	{type:'numbers', title:'序号'}
        	,{type:'checkbox'}
			,{field: 'customerId', title: '客户编码', minWidth:'150'}
    		,{field: 'customerName', title: '客户', minWidth:'150'}
			,{field: 'productId', title: '产品编码', minWidth:'150'}
    		,{field: 'productName', title: '产品', minWidth:'150'}
    		,{field: 'type', title: '类型', minWidth:'90'}
    		,{field: 'pricingMethod', title: '计价方式', minWidth:'80'}
    		,{field: 'orderProcessName', title: '订单工序', minWidth:'120'}
    		,{field: 'orderPrice', title: '工序价格', minWidth:'90'}
    		,{field: 'expectHours', title: '工序标准工时', minWidth:'90'}
    		,{field: 'createUserName', title: '创建人', minWidth:'80', hide: true}
    		,{field: 'createTime', title: '创建时间', minWidth:'120', hide: true}
        ]]
    	,text: {
    		none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
    	}
    	,toolbar:'#tableToolbar'
    	,defaultToolbar: ['filter']
    });

	table.render({
		elem:'#produceTable'
		,height: 'full-120'
		,page: true //开启分页
		,limit: 10
		,limits: [10,15,20,30,40,50,100]
		,cols: [[ //表头
			{type:'numbers', title:'序号'}
			,{type:'checkbox'}
			,{field: 'produceProcessName', title: '加工工序', minWidth:'120'}
			,{field: 'producePrice', title: '工序价格', minWidth:'90'}
			,{field: 'createUserName', title: '创建人', minWidth:'80', hide: true}
			,{field: 'createTime', title: '创建时间', minWidth:'120', hide: true}
		]]
		,data: []
		,text: {
			none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
		}
		,toolbar:'#produceTableToolbar'
		,defaultToolbar: ['filter']
	});
	
	//监听行单击事件
	table.on('row(table)', function(obj){
		table.reload('produceTable',{
			url:'/manage/process_price_order/list_produce'
			,where: {orderId:obj.data.id}
		})
		tableSelect = obj.data.id;
		$("#findMsg").html('查询条件：');
	});

	// var dataFields = [
	// 	{field:"customer_id", title:"客户", edit:"select", templet:"#customer"}
	// 	,{field:"product_id", title:"产品", edit:"select", templet:"#product"}
	// 	,{field:"type", title:"类型", edit:"text"}
	// 	,{field:"order_process_d", title:"订单工序", edit:"select", templet:"#process"}
	// ];
	var dataFields = [
		{field:"customer_id", title:"客户编码", edit:"select", templet:"#customer"}
		// ,{field: "customer_name",title: "客户名称",edit: "select",templet: "#customer"}
		,{field:"product_id", title:"产品编码", edit:"select", templet:"#product"}
		// ,{field:"product_name", title:"产品名称", edit:"select", templet:"#product"}
		,{field:"type", title:"类型", edit:"text"}
		,{field:"pricing_method", title:"计价方式（计件、计时）", edit:"text"}
		,{field:"expect_hours", title:"标准工时", edit:"text"}
		,{field:"order_process_code", title:"工序编码", edit:"select", templet:"#process"}
		// ,{field:"order_process_name", title:"工序名称", edit:"select", templet:"#process"}
		,{field:"order_price", title:"单价", edit:"text"}
	];
	var top_dc = undefined;
	var dc = dynamicCondition.create({
    	fields:dataFields
	  	,tableId:"table" 
		,conditionTextId:"#findMsg"
		,type:"complex" 
	  	,requestDataType:"json"
	  	,counts:5
		,queryCallBack:function(requestData){}
		,afterOpen: function (_dc) {
			top_dc = _dc;
		}
	});
	
    table.on('toolbar(table)', function(obj){
    	var tableCheckData = table.checkStatus(obj.config.id).data;
		switch(obj.event){
			case 'find':
				dc.open();
			break;
		    case 'add':
		    	var index = layer.open({
		    		type: 2
		    		,title: "新增"
		    		,maxmin: true
		    	  	,area: ['50%', '100%']
		    	  	,content: '/manage/process_price_order/addOrderHtml'
		    	  	,offset: 'r'
		    	  	,btn: ['保存','返回']
		        	,yes: function(index, layero){
		        		var body = layer.getChildFrame('body', index);
				  		var iframeWindow = $(layero).find("iframe")[0].contentWindow;
				  		var data = iframeWindow.getFormDataAndValidate();
				  		if(!data[0]){
				  			return;
				  		}
		        		var obj = data[1];
		        		var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
		        		$.ajax({ 
							url: "/manage/process_price_order/add_order",
							type: "post",
							data: obj,
							success: function (d) {
								if(d.code == '200'){
									top.layer.msg("新增成功",{icon:1});
									layer.close(index);
								}else{
									top.layer.msg("新增失败，"+d.msg,{icon:2});
								}
								top.layer.close(shadeIndex);
								table.reload('table');
							},
							error: function () {
								top.layer.close(shadeIndex);
								alert("新增失败！");
							}
						})
		    		}
		    	});
		    break;
		    case 'upd':
		    	if(tableCheckData.length != 1){
					top.layer.msg("请选择单个数据");
					return;
		    	}
		    	var index = layer.open({
		    		type: 2
		    		,title: "修改"
		    		,maxmin: true
		    	  	,area: ['50%', '100%']
		    		,offset: 'r'
		    	  	,content: '/manage/process_price_order/updateOrderHtml?id='+tableCheckData[0].id
		    	  	,btn: ['保存','返回']
		        	,yes: function(index, layero){
		        		var body = layer.getChildFrame('body', index);
				  		var iframeWindow = $(layero).find("iframe")[0].contentWindow;
				  		var data = iframeWindow.getFormDataAndValidate();
				  		if(!data[0]){
				  			return;
				  		}
		        		var obj = data[1];
		        		obj.id = tableCheckData[0].id;
		        		var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
		        		$.ajax({ 
							url: "/manage/process_price_order/update_order",
							type: "post",
							data: obj,
							success: function (d) {
								if(d.code == '200'){
									top.layer.msg("修改成功",{icon:1});
									layer.close(index);
								}else{
									top.layer.msg("修改失败，"+d.msg,{icon:2});
								}
								top.layer.close(shadeIndex);
								table.reload('table');
							},
							error: function () {
								top.layer.close(shadeIndex);
								alert("修改失败！");
							}
						})
		    		}
		    	});
		    break;
		    case 'del':
		    	if(tableCheckData.length == 0){
					layer.msg("请选择数据");
					return;
		    	}
		    	top.layer.confirm('删除订单工序价格表将会同时删除加工工序价格表信息，是否删除?', {icon: 3, title:'提示'}, function(index){
		    		var ids = new Array();
			    	$.each(tableCheckData,function(index, e){
						ids.push(e.id);
			    	});
			    	var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
			    	$.ajax({
						url: "/manage/process_price_order/delete_order",
						type: "post",
						data: JSON.stringify(ids),
						contentType:"application/json",
						success: function (d){
							if(d.code == '200'){
								top.layer.alert("删除成功",{icon:1});
							}else{
								top.layer.msg("删除失败，"+d.msg,{icon:2});
							}
							top.layer.close(shadeIndex);
							table.reload('table');
							table.reload('produceTable');
						},
						error: function(){
							top.layer.close(shadeIndex);
							alert("删除失败！");
						}
					});
		    		top.layer.close(index);
		    	});
		    break;
			case 'save':
				// var index = layui.layer.open({
				// type: 2
				// ,title: "请选择要导入的数据"
				// ,content: '/manage/process_price_order/saveOrderHtml'
				// ,area: ['700px', '500px']
				// ,btn: ["确定","取消"]
				// ,yes: function(index, layero){
				// 		var body = layer.getChildFrame('body', index);
				// 		var iframeWindow = $(layero).find("iframe")[0].contentWindow;
				// 		var data = iframeWindow.getFormDataAndValidate();
				// 		if(!data[0]){
				// 			return;
				// 		}
				// 		var obj = data[1];
				// 		console.log(obj)
				//
				// 		layui.layer.close(index);
					layer.confirm('是否进行补差导入', {
							btn: ['补差','取消'] //按钮
						}
						// ,function () {
						// 	upload_type = "cover";
						// 	$("#uploadExcel")[0].click();
						// }
						,
						function chayi() {
							upload_type = "difference";
							$("#uploadExcel")[0].click();
							return false;
						})
				// }
			// });
				break;
		    case 'download':
				layer.confirm('确定要导出数据并下载到本地吗？', function (index) {
					var conditionArray = new Array();
					if (top_dc != undefined) {
						for (let i in top_dc.cacheCondition) {
							if (top_dc.cacheCondition[i].conditionValueLeftVal.value != ''
								|| top_dc.cacheCondition[i].conditionValueRightVal.value != '' || top_dc.cacheCondition[i].conditionValueVal.value != '') {
								var condition = {
									field: top_dc.cacheCondition[i].conditionFieldVal
									,title: top_dc.data[i].title
									,type: top_dc.cacheCondition[i].conditionOptionVal
									,right: top_dc.cacheCondition[i].conditionValueRightVal.value
									,left: top_dc.cacheCondition[i].conditionValueLeftVal.value
									,value: top_dc.cacheCondition[i].conditionValueVal.value
								}
								conditionArray.push(condition);
							}
						}
					}
					window.location.href = "/manage/process_price_order/download?condition=" + encodeURI(JSON.stringify(conditionArray));
					layer.close(index);

				});
				break;
		    case 'upload':
		    	$("#uploadExcel")[0].click();
		    break;
		};
	});
    
    table.on('toolbar(produceTable)', function(obj){
    	var tableCheckData = table.checkStatus(obj.config.id).data;
    	switch(obj.event){
	    	case 'produce_add':
	    		if(tableSelect == undefined){
	    			layer.msg("请先选择订单工序！");
	    			return;
	    		}
	    		var index = layer.open({
	    			type: 2
	    			,title: "新增"
					,maxmin: true
					,area: ['40%', '100%']
	    			,content: '/manage/process_price_order/addProduceHtml'
	    			,offset: 'r'
	    			,btn: ['保存','返回']
		    		,yes: function(index, layero){
		    			var body = layer.getChildFrame('body', index);
		    			var iframeWindow = $(layero).find("iframe")[0].contentWindow;
		    			var data = iframeWindow.getFormDataAndValidate();
		    			if(!data[0]){
		    				return;
		    			}
		    			var obj = data[1];
		    			obj.orderId = tableSelect
		    			var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
		    			$.ajax({ 
		    				url: "/manage/process_price_order/add_produce",
		    				type: "post",
		    				data: obj,
		    				success: function (d) {
		    					if(d.code == '200'){
		    						top.layer.msg("新增成功",{icon:1});
		    						layer.close(index);
		    					}else{
		    						top.layer.msg("新增失败，"+d.msg,{icon:2});
		    					}
		    					top.layer.close(shadeIndex);
		    					table.reload('produceTable');
		    				},
		    				error: function () {
		    					top.layer.close(shadeIndex);
		    					alert("新增失败！");
		    				}
		    			})
		    		}
	    		});
    		break;
	    	case 'produce_upd':
	    		if(tableCheckData.length != 1){
	    			top.layer.msg("请选择单个数据");
	    			return;
	    		}
	    		var index = layer.open({
	    			type: 2
	    			,title: "修改"
					,maxmin: true
					,area: ['40%', '100%']
	    			,offset: 'r'
	    			,content: '/manage/process_price_order/updateProduceHtml?id='+tableCheckData[0].id
	    			,btn: ['保存','返回']
		    		,yes: function(index, layero){
		    			var body = layer.getChildFrame('body', index);
		    			var iframeWindow = $(layero).find("iframe")[0].contentWindow;
		    			var data = iframeWindow.getFormDataAndValidate();
		    			if(!data[0]){
		    				return;
		    			}
		    			var obj = data[1];
		    			obj.id = tableCheckData[0].id;
		    			var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
		    			$.ajax({ 
		    				url: "/manage/process_price_order/update_produce",
		    				type: "post",
		    				data: obj,
		    				success: function (d) {
		    					if(d.code == '200'){
		    						top.layer.msg("修改成功",{icon:1});
		    						layer.close(index);
		    					}else{
		    						top.layer.msg("修改失败，"+d.msg,{icon:2});
		    					}
		    					top.layer.close(shadeIndex);
		    					table.reload('produceTable');
		    				},
		    				error: function () {
		    					top.layer.close(shadeIndex);
		    					alert("修改失败！");
		    				}
		    			})
		    		}
	    		});
    		break;
	    	case 'produce_del':
	    		if(tableCheckData.length == 0){
	    			layer.msg("请选择数据");
	    			return;
	    		}
	    		top.layer.confirm('是否删除?', {icon: 3, title:'提示'}, function(index){
	    			var ids = new Array();
	    			$.each(tableCheckData,function(index, e){
						ids.push(e.id);
	    			});
	    			var shadeIndex = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.4});
	    			$.ajax({
	    				url: "/manage/process_price_order/delete_produce",
	    				type: "post",
	    				data: JSON.stringify(ids),
	    				contentType:"application/json",
	    				success: function (d){
	    					if(d.code == '200'){
	    						top.layer.msg("删除成功",{icon:1});
	    					}else{
	    						top.layer.msg("删除失败",{icon:2});
	    					}
	    					top.layer.close(shadeIndex);
	    					table.reload('produceTable');
	    				},
	    				error: function(){
	    					top.layer.close(shadeIndex);
	    					alert("删除失败！");
	    				}
	    			});
	    			top.layer.close(index);
	    		});
    		break;
    	};
    });
    
    //拖拽上传
	upload.render({
		elem: '#uploadExcel'
		,accept: 'file' //普通文件
		,exts: 'xlsx|xls'
		,auto: false
		,choose: function(obj){
			var files = obj.pushFile()
			var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下
			var fields = {
				'customerId' : 'D',
				'customerName' : 'H',
				'productId' : 'E',
				'productName' : 'F',
				'type' : 'I',
				'pricingMethod' : 'M',
				'expectHours' : 'L',
				'orderProcessCode' : 'G',
				'orderProcessName' : 'K',
				'orderPrice' : 'N',
			}
			// 用完就清理掉，避免多次选中相同文件时出现问题
			for (var index in files) {
				if (files.hasOwnProperty(index)) {
					delete files[index]
				}
			}
			$('#uploadExcel').next().val('');
			uploadExcel('/manage/process_price_order/upload/',fields,fileArr,excel,layer,laytpl,element,table)
		}
	});
})
